package com.example.qrcodecamera;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;

import java.util.List;

public class MaterialCSVViewActivity extends AppCompatActivity {
    private static final int PAGE_SIZE = 15;
    private MaterialCSVDbHelper dbHelper;
    private TableLayout tableLayout;
    private TextView tvPageInfo;
    private Button btnPrev, btnNext;
    private int currentPage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_csvview);

        // 初始化组件
        dbHelper = new MaterialCSVDbHelper(this);
        tableLayout = findViewById(R.id.tbl_data);
        tvPageInfo = findViewById(R.id.tv_page_info);
        btnPrev = findViewById(R.id.btn_prev);
        btnNext = findViewById(R.id.btn_next);

        // 设置分页按钮监听
        btnPrev.setOnClickListener(v -> loadPage(currentPage - 1));
        btnNext.setOnClickListener(v -> loadPage(currentPage + 1));

        // 加载首屏数据
        loadPage(1);
    }

    private void loadPage(int page) {
        int total = dbHelper.getTotalCount();
        int totalPages = (int) Math.ceil((double) total / PAGE_SIZE);

        if (page < 1 || page > totalPages) return;
        currentPage = page;

        tableLayout.removeAllViews();

        // 添加表头
        TableRow header = createHeaderRow();
        tableLayout.addView(header);

        // 获取数据
        List<MaterialCSVRecord> records = dbHelper.getPagedData(currentPage, PAGE_SIZE);
        for (MaterialCSVRecord record : records) {
            TableRow row = createDataRow(record);
            tableLayout.addView(row);
        }

        updatePaginationUI(totalPages);
    }


    // 修改表头和数据行映射
    private TableRow createHeaderRow() {
        TableRow row = new TableRow(this);
        String[] headers = {"物料编号", "物料名称", "总重量", "当前重量", "入库时间"};
        for (String header : headers) {
            TextView tv = new TextView(this);
            tv.setText(header);
            tv.setBackgroundResource(R.drawable.table_header_bg);
            tv.setPadding(16, 12, 16, 12);
            row.addView(tv);
        }
        return row;
    }

    private TableRow createDataRow(MaterialCSVRecord record) {
        TableRow row = new TableRow(this);
        String[] values = {
                record.getMaterialId(),
                record.getMaterialName(),
                String.format("%.2f", record.getTotalWeight()),
                String.format("%.2f", record.getCurrentWeight()),
                record.getStorageTime()
        };

        // 添加数据列
        for (String value : values) {
            TextView tv = new TextView(this);
            tv.setText(value);
            tv.setPadding(16, 8, 16, 8);
            row.addView(tv);
        }

        // 添加删除按钮
        Button btnDelete = new Button(this);
        btnDelete.setText("删除");
        btnDelete.setOnClickListener(v -> {
            // 弹出确认对话框
            new AlertDialog.Builder(this)
                    .setTitle("确认删除")
                    .setMessage("确定要删除这条记录吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 在子线程中执行删除操作
                        new Thread(() -> {
                            boolean success = dbHelper.deleteRecord(record.getId());
                            runOnUiThread(() -> {
                                if (success) {
                                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                                    loadPage(currentPage); // 刷新当前页
                                } else {
                                    Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }).start();
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
        row.addView(btnDelete);

        return row;
    }


    private void updatePaginationUI(int totalPages) {
        tvPageInfo.setText(String.format("第 %d 页/共 %d 页", currentPage, totalPages));
        btnPrev.setEnabled(currentPage > 1);
        btnNext.setEnabled(currentPage < totalPages);
    }

    @Override
    protected void onDestroy() {
        dbHelper.close();
        super.onDestroy();
    }
}